package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoBean;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoTypeBean;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoTypeList;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.NewListAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.SubscriptionNoAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.SubscriptionNoTypeAdapter;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.KeyBoardUtils;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 更多订阅号
 */
public class MoreSubscriptionNoActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , SubscriptionNoTypeAdapter.OnTypeClickListener, SubscriptionNoAdapter.OnSubscriptionNoClickListener {

    @BindView(R.id.input_key)
    protected EditText searchKey;
    @BindView(R.id.left_list)
    protected RecyclerView leftListRecyclerView;

    @BindView(R.id.refresh_layout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    public static final String SUBSCRIPTION_TYPE_URL = "sctv/bumenxiangzhen/index/bumenxiangzhen.json";
    public static final String SUBSCRIPTION_NO_TYPE_ID = "subscription_no_type_ID";
    private String getSubscriptionNoTypeId;
    private SubscriptionNoTypeAdapter typeAdapter;
    private SubscriptionNoAdapter adapter;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<FocusColumn> subscriptionNoTypeList = new ArrayList<>();
    private List<SubscriptionNoTypeBean> typeList = new ArrayList<>();
    private List<SubscriptionNoBean> dataList = new ArrayList<>();
    private List<String> authorList = new ArrayList<>();
    private int currentTagIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        new TitleUtils(this).useAndSetTxTitle("订阅号");
        getSubscriptionNoTypeId = getIntent().getStringExtra(SUBSCRIPTION_NO_TYPE_ID);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_more_subscription_no);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        leftListRecyclerView.setItemAnimator(new DefaultItemAnimator());
        leftListRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mRefreshLayout.setLoadMoreEnabled(false);
        mRefreshLayout.setRefreshEnabled(false);
//        mRefreshLayout.setOnRefreshListener(this);
//        mRefreshLayout.setOnLoadMoreListener(this);
//        mRefreshLayout.setLoadMoreEnabled(false);
//        mRefreshLayout.setRefreshEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        //设置布局管理器， 参数gridLayoutManager对象
        mRecyclerView.setLayoutManager(gridLayoutManager);

        getSubscriptionNoTypeArray(SUBSCRIPTION_TYPE_URL);
        searchKey.clearFocus();
        KeyBoardUtils.closeKeyboard(this);
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {

    }
    /**
     * 获取 订阅号类型数据
     *
     * @param url
     */
    private void getSubscriptionNoTypeArray(String url) {
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), url, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            boolean canComplete = true;

            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case 0:
                                    subscriptionNoTypeList.add(fc);
                                    break;
                            }
                        }
                    }
                    getSubscriptionNoTypeArray();
                } else{
                    toast("数据异常");
                }

            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }

    /**
     * 获取 订阅号类型数据
     *
     */
    private void getSubscriptionNoTypeArray() {
        if (ListUtils.isListValued(subscriptionNoTypeList)) {
            for (FocusColumn fc : subscriptionNoTypeList) {
                if (fc != null) {
                    SubscriptionNoTypeBean bean = new SubscriptionNoTypeBean();
                    bean.setChannelId("" + fc.getChannelId());
                    bean.setChannelName(fc.getChannelName());
                    bean.setChannelUrl(fc.getChannelUrl());
                    typeList.add(bean);
                }
            }
            initTypeData();
        }else{
            toast("数据异常");
        }

    }
    /**
     * 获取某类型的订阅号
     */
    private void getData(String url) {
        NetUtils.getNetAdapter().getSubscriptionNoList(getOwnerName(), url, new AbsListNetCallback<SubscriptionNoBean>(ListTypeUtils.SubscriptionNoBean(), 0) {
            @Override
            public void onSuc(List<SubscriptionNoBean> nobeanList) {
                if (ListUtils.isListValued(nobeanList)) {
                    typeList.get(currentTagIndex).setSubscriptionNoList(nobeanList);
                    initData(nobeanList);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });

    }



    private void initTypeData() {
        if (null == adapter) {
            typeAdapter = new SubscriptionNoTypeAdapter(this, this);
            typeAdapter.setData(typeList);
            leftListRecyclerView.setAdapter(typeAdapter);
            typeAdapter.notifyDataSetChanged();
        }
        if (ListUtils.isListValued(typeList)) {
            for (int i = 0; i < typeList.size(); i++) {
                if (typeList.get(i).getChannelId().equalsIgnoreCase(getSubscriptionNoTypeId)) {
                    currentTagIndex = i;
                    typeList.get(i).setSelected(true);
                    dataList.clear();
                    getData(typeList.get(currentTagIndex).getChannelUrl());
                } else {
                    typeList.get(i).setSelected(false);
                }
            }
        }
    }

    private void initData(List<SubscriptionNoBean> subscriptionNoItems) {
        if (null == adapter) {
            adapter = new SubscriptionNoAdapter(this, subscriptionNoItems, this);
            mRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(subscriptionNoItems);
        }

    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(false);

    }

    @Override
    public void OnTypeClick(int position) {

        for (int i = 0; i < typeList.size(); i++) {
            if (i == position) {
                typeList.get(i).setSelected(true);
            } else {
                typeList.get(i).setSelected(false);
            }
        }
        typeAdapter.setData(typeList);
        //TODO 选择类型
        currentTagIndex = position;
        dataList.clear();
        if (ListUtils.isListValued(typeList.get(currentTagIndex).getSubscriptionNoList())) {
            dataList.addAll(typeList.get(currentTagIndex).getSubscriptionNoList());
            adapter.setData(dataList);
        } else {
            getData(typeList.get(currentTagIndex).getChannelUrl());
        }

    }

    @Override
    public void OnSubscriptionNoClick(SubscriptionNoBean bean) {
        //TODO 点击订阅号
        Intent intent = new Intent(this, SubscriptionNoDetailActivity.class);
        intent.putExtra(SubscriptionNoDetailActivity.SUBSCRIPTION_NO_ID, bean.getWxId());
        intent.putExtra(BaseActivity.EX_TITLE, bean.getWxName());
        startActivity(intent);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            //TODO  搜索
            String key = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("请输入关键词");
            } else {
                Intent intent = new Intent(this, SearchSubscriptionNoActivity.class);
                intent.putExtra(SearchSubscriptionNoActivity.INPUT_KEY, key);
                startActivityForResult(intent, 1);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                mRefreshLayout.autoRefresh();
                setResult(RESULT_OK);
            }
        }
    }

    @OnClick(value = {R.id.title_top_back})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                onBackPressed();
                break;

        }
    }

}
